<template>
    <div class="drag-container">
        <h2>拖拽排序示例</h2>
        <div class="drag-list">
            <div
                v-for="(item, index) in items"
                :key="item.id"
                class="drag-item"
                :draggable="true"
                @dragstart="handleDragStart(index)"
                @dragover.prevent="handleDragOver(index)"
                @dragend="handleDragEnd"
                @drop.prevent="handleDrop(index)"
                :class="{ 'dragging': draggingIndex === index }"
            >
                {{ item.name }}
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            items: [
                { id: 1, name: '项目 1' },
                { id: 2, name: '项目 2' },
                { id: 3, name: '项目 3' },
                { id: 4, name: '项目 4' },
                { id: 5, name: '项目 5' }
            ],
            draggingIndex: null,
            dropIndex: null
        };
    },
    methods: {
        handleDragStart(index) {
            // 记录开始拖拽的元素索引
            this.draggingIndex = index;
        },
        handleDragOver(index) {
            // 记录当前拖拽经过的元素索引
            this.dropIndex = index;
        },
        handleDragEnd() {
            // 拖拽结束，重置状态
            this.draggingIndex = null;
            this.dropIndex = null;
            // 移除所有拖拽样式
            document.querySelectorAll('.drag-item').forEach(item => {
                item.classList.remove('dragging');
            });
        },
        handleDrop(index) {
            // 当拖拽源和目标不同时才执行排序
            if (this.draggingIndex !== index) {
                // 复制原数组
                const newItems = [...this.items];
                // 移除拖拽的元素
                const [removedItem] = newItems.splice(this.draggingIndex, 1);
                // 将移除的元素插入到新位置
                newItems.splice(index, 0, removedItem);
                // 更新数据
                this.items = newItems;
            }
            // 重置状态
            this.handleDragEnd();
        }
    }
};
</script>

<style scoped>
.drag-container {
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
}

.drag-list {
    display: flex;
    gap: 10px;
    overflow-x: auto;
    padding: 10px 0;
    min-height: 120px;
    border: 2px dashed #ccc;
    border-radius: 8px;
}

.drag-item {
    background-color: #42b983;
    color: white;
    padding: 20px 30px;
    border-radius: 6px;
    cursor: move;
    transition: all 0.3s ease;
    flex-shrink: 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.drag-item:hover {
    background-color: #359e75;
    transform: translateY(-2px);
}

.drag-item.dragging {
    opacity: 0.5;
    transform: scale(1.05);
    background-color: #2d8b68;
}

.drag-list.dragover {
    border-color: #42b983;
}
</style>
